<template>
  <el-container>
    <el-header>
      <div class="left-panel">
        <el-button
            type="primary"
            plain
            icon="el-icon-plus"
            @click="handleAdd"
        >新增
        </el-button>
        <el-button
            type="success"
            plain
            icon="el-icon-edit"
            :disabled="single"
            @click="handleUpdate"
        >修改
        </el-button>
        <el-button
            type="danger"
            plain
            icon="el-icon-delete"
            :disabled="multiple"
            @click="handleDelete"
        >删除
        </el-button>
      </div>
      <div class="right-panel">
        <jcx-table-bar v-model:showSearch="showSearch" @queryTable="getList" :columns="columns"></jcx-table-bar>
      </div>
    </el-header>

    <el-main>
      <el-form :model="queryParams" ref="queryForm" size="default" :inline="true" v-show="showSearch"
               label-width="68px">
        <el-row>
          <el-col :span="8">
            <el-form-item label="部门名称" prop="deptName">
              <el-input
                  v-model="queryParams.deptName"
                  placeholder="请输入部门名称"
                  clearable
                  @keyup.enter.native="handleQuery"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="部门状态" prop="status">
              <el-select v-model="queryParams.status" placeholder="部门状态" clearable>
                <el-option key="1" label="启用" :value="true"/>
                <el-option key="0" label="停用" :value="false"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item>
              <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
              <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <el-table ref="table" v-loading="loading" :data="deptList" row-key="deptId"
                @selection-change="handleSelectionChange"
                :stripe="config.stripe" :border="config.border" :size="config.size" style="width: 100%">
        <el-table-column type="selection"></el-table-column>
        <el-table-column label="部门标识" align="center" prop="deptCode" v-if="columns[0].visible"></el-table-column>
        <el-table-column label="部门名称" align="center" prop="deptName" v-if="columns[1].visible"></el-table-column>
        <el-table-column label="联系电话" align="center" prop="phone" v-if="columns[2].visible"></el-table-column>
        <el-table-column label="联系邮箱" align="center" prop="email" v-if="columns[3].visible"></el-table-column>
        <el-table-column label="负责人名称" align="center" prop="leaderUserName" v-if="columns[4].visible"></el-table-column>
        <el-table-column label="排序" align="center" prop="sort" v-if="columns[5].visible"></el-table-column>
        <el-table-column label="状态" align="center" prop="status" v-if="columns[6].visible">
          <template #default="props">
            <el-tag v-if="props.row.status" type="success">启用</el-tag>
            <el-tag v-if="!props.row.status" type="danger">停用</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="创建时间" align="center" prop="createTime" v-if="columns[7].visible"></el-table-column>
        <el-table-column label="备注" align="center" prop="remark" v-if="columns[8].visible"></el-table-column>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="props">
            <el-button
                size="mini"
                type="text"
                icon="el-icon-edit"
                @click="handleUpdate(props.row)"
            >修改
            </el-button>
            <el-button
                size="mini"
                type="text"
                icon="el-icon-delete"
                @click="handleDelete(props.row)"
            >删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <el-dialog destroy-on-close append-to-body width="900px" :title="title" v-model="open"
                 :close-on-click-modal="false" @closed="cancel">
        <el-form ref="form" :model="form" :rules="rules" label-width="100px">
          <el-row>
            <el-col :span="12">
              <el-form-item label="上级部门" prop="parentId">
                <el-cascader v-model="form.parentId" :options="parentDeptList" :props="deptProps"
                             :show-all-levels="false"
                             clearable style="width: 100%;"></el-cascader>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="部门负责人" prop="leaderUserId">
                <el-select v-model="form.leaderUserId" placeholder="请选择" style="width: 100%;">
                  <el-option
                      v-for="user in userList"
                      :key="user.userId"
                      :label="user.nickName"
                      :value="user.userId">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="部门标识" prop="deptCode">
                <el-input v-model="form.deptCode" clearable placeholder="请输入部门标识"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="部门名称" prop="deptName">
                <el-input v-model="form.deptName" clearable placeholder="请输入部门名称"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="联系电话" prop="phone">
                <el-input v-model="form.phone" clearable placeholder="请输入联系电话"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="部门邮箱" prop="email">
                <el-input v-model="form.email" clearable placeholder="请输入部门邮箱"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="排序" prop="sort">
                <el-input-number v-model="form.sort" :min="1" :precision="2" :step="0.1" controls-position="right"
                                 style="width: 100%;"></el-input-number>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="是否有效" prop="status">
                <el-switch v-model="form.status" :active-value="true" :inactive-value="false"></el-switch>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <el-form-item label="备注" prop="remark">
                <el-input type="textarea" v-model="form.remark" clearable placeholder="请输入备注"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
        <template #footer>
          <el-button type="primary" :loading="saveing" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </template>
      </el-dialog>
    </el-main>
  </el-container>
</template>

<script>
export default {
  name: "Dept",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 保存遮罩层
      saveing: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 部门列表数据
      deptList: [],
      // 父部门列表
      parentDeptList: [],
      // 用户列表
      userList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        deptName: undefined,
        status: undefined
      },
      // 表单参数
      form: {},
      // 部门子父关系
      deptProps: {
        value: "deptId",
        label: "deptName",
        emitPath: false,
        checkStrictly: true
      },
      // 表单校验
      rules: {
        sort: [
          {required: true, message: '请输入排序', trigger: 'change'}
        ],
        deptCode: [
          {required: true, message: '请输入部门标识', trigger: 'blur'}
        ],
        deptName: [
          {required: true, message: '请输入部门名称', trigger: 'blur'}
        ],
        leaderUserId: [
          {required: true, message: '请输入部门负责人', trigger: 'blur'}
        ],
        phone: [
          {required: true, message: '请输入联系电话', trigger: 'blur'}
        ],
        email: [
          {required: true, message: '请输入联系邮箱', trigger: 'blur'}
        ]
      },
      // 表格配置
      config: {
        // 表格大小
        size: "default",
        // 表格边框
        border: true,
        // 表格斑马图纹
        stripe: true
      },
      columns: [
        {key: 0, label: `部门标识`, visible: true},
        {key: 1, label: `部门名称`, visible: true},
        {key: 2, label: `联系电话`, visible: true},
        {key: 3, label: `联系邮箱`, visible: true},
        {key: 4, label: `负责人名称`, visible: true},
        {key: 5, label: `排序`, visible: true},
        {key: 6, label: `状态`, visible: true},
        {key: 7, label: `创建时间`, visible: false},
        {key: 8, label: `备注`, visible: true}
      ],
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询部门列表 */
    getList() {
      this.loading = true;
      if (this.userList.length === 0) {
        this.$API.user.pageListUser.get({status: true}).then(response => {
          if (response.status) {
            this.userList = response.data.records;
          } else {
            this.$message.warning(response.msg);
          }
        });
      }
      this.$API.dept.pageListDept.get({status: true}).then(response => {
        if (response.status) {
          this.parentDeptList = response.data.records;
        } else {
          this.$message.warning(response.msg);
        }
      });
      this.$API.dept.pageListDept.get(this.queryParams).then(response => {
        if (response.status) {
          this.deptList = response.data.records
        } else {
          this.$message.warning(response.msg);
        }
        this.loading = false;
      })
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.saveing = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        deptId: "",
        parentId: "",
        deptCode: "",
        deptName: "",
        leaderUserId: "",
        phone: "",
        email: "",
        sort: 1,
        remark: '',
        status: true
      };
      this.$nextTick(() => {
        if (this.$refs['form']) {
          this.$refs['form'].clearValidate();
          this.$refs['form'].resetFields();
        }
      });
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.$refs["queryForm"].resetFields();
      this.handleQuery();
    },
    /** 多选框选中数据 */
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.deptId);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加部门";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const deptId = row.deptId || this.ids
      this.$API.dept.getDeptById.get(deptId).then(response => {
        if (response.status) {
          this.form = response.data;
          this.open = true;
          this.title = "修改部门";
        } else {
          this.$message.warning(response.msg);
        }
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.saveing = true;
          // 如果 ID 存在就是更新
          if (this.form.deptId) {
            this.$API.dept.editDept.put(this.form).then(response => {
              if (response.status) {
                this.$message.success(response.msg);
                this.saveing = false;
                this.open = false;
                this.getList();
              } else {
                this.$alert(response.msg, "提示", {type: 'error'});
                this.saveing = false;
              }
            });
          } else {
            // 不存在就是新增
            this.$API.dept.addDept.post(this.form).then(response => {
              if (response.status) {
                this.$message.success(response.msg);
                this.saveing = false;
                this.open = false;
                this.getList();
              } else {
                this.$alert(response.msg, "提示", {type: 'error'});
                this.saveing = false;
              }
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const deptIds = row.deptId ? [row.deptId] : this.ids;
      this.$confirm(`确定删除选中的 ${deptIds.length} 项吗？`, '提示', {
        type: 'warning'
      }).then(() => {
        this.$API.dept.delDepts.delete(deptIds).then(response => {
          if (response.status) {
            this.$message.success(response.msg);
            this.getList();
          } else {
            this.$alert(response.msg, "提示", {type: 'error'});
          }
        });
      }).catch(() => {
      })
    }
  }
};
</script>
